import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../constant/app_constant.dart';
import '../../../model/member_info.dart';
import '../../../model/push_model.dart';
import '../../../public/empty_widget.dart';
import '../../../public/event_bus.dart';
import 'client_service_detail.dart';

/// @class : client_msg_list
/// @date : 2023-02-26 13:07
/// @name : LFC
/// @description : 服务及优惠
class ServiceDiscountList extends StatefulWidget {
  const ServiceDiscountList({Key? key}) : super(key: key);

  @override
  State<ServiceDiscountList> createState() => _ClientMsgLIstState();
}

class _ClientMsgLIstState extends State<ServiceDiscountList>
    with AutomaticKeepAliveClientMixin {
  PushModel? model;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制

  final RefreshController _refreshController1 =
      RefreshController(initialRefresh: false); // 刷新控件控制

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
    _refreshController1.dispose();
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  List<Rows> rows = [];
  int pageNum = 1;

  loadData({isShowLoading = true}) {
    if (isShowLoading) {
      Obj.showLoading();
    }
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      MemberInfo memberInfo = MemberInfo.fromJson2(json);
      final params = {
        "membersId": memberInfo.data?.membersId,
        "kind": "0",
        "pageNum": pageNum
      };
      Apis.getPushList(params).then((response) {
        Obj.dismissLoading();
        var data = response?.data;
        model = PushModel.fromJson(data);
        rows.addAll(model?.rows ?? []);
        setState(() {});
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
        _refreshController1.refreshCompleted();

        if ((rows.length) >= (model?.total ?? 0)) {
          LogUtil.d("loadNoData loadNoData ${model?.total}");
          _refreshController.loadNoData();
          return;
        }
      }).onError((error, stackTrace) {
        LogUtil.d("pushList $error");
        Obj.dismissLoading();
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
        _refreshController1.refreshCompleted();
      });
    }
  }

  loadMoreData() {
    if (rows.length >= (model?.total ?? 0)) {
      _refreshController.loadNoData();
      return;
    }
    pageNum += 1;
    loadData(isShowLoading: false);
  }

  Widget messageItem(Rows item) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  "${item.informComment}",
                  maxLines: 3,
                  style: getTextStyle(24.sp,
                      fontType: FontType.MID, color: Styles.c_191919),
                ),
              ),
              SizedBox(
                width: 20.w,
              ),
              Container(
                margin: EdgeInsets.only(top: 10.w),
                alignment: Alignment.topRight,
                child: Text(
                  "${item.createTime}",
                  maxLines: 3,
                  style: getTextStyle(14.sp,
                      fontType: FontType.MID, color: Styles.c_666),
                ),
              ),
            ],
          ),
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12),
            width: double.infinity,
            child: item.readFlag == "0"
                ? Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text("新消息",
                          style: getTextStyle(14.sp,
                              fontType: FontType.BOLD,
                              color: Colors.redAccent)),
                      const SizedBox(
                        width: 4,
                      ),
                      Container(
                        width: 6,
                        height: 6,
                        decoration: BoxDecoration(
                            color: Colors.redAccent,
                            borderRadius: BorderRadius.circular(3)),
                      )
                    ],
                  )
                : Container(),
          ),
        ],
      ),
    ).setOnClickListener(() async {
      messageRead(item);
    });
  }

  messageRead(Rows item) {
    Obj.showLoading();
    Apis.messageReadSet({"longList": item.informId.toString()})
        .then((response) {
      print('messageReadSet response');
          print(response);
      Obj.dismissLoading();
      _refreshController.refreshCompleted();
      item.readFlag = "1";
      setState(() {});
      Get.to(ClientServiceDetailPage(text: item.informComment ?? ""));
      eventBus.fire(UpdateMsgReadEvent());
    }).onError((error, stackTrace) {
      _refreshController.refreshCompleted();
      Obj.dismissLoading();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (rows.isEmpty) {
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        controller: _refreshController1,
        onRefresh: _onRefresh,
        child: const EmptyWidget(
          emptyText: '暂無通知數據',
        ),
      );
    }
    return Scaffold(
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: () {
          loadMoreData();
        },
        child: ListView.separated(
            shrinkWrap: true,
            itemCount: rows.length,
            itemBuilder: (context, index) {
              return messageItem(rows[index]);
            },
            separatorBuilder: (context, index) {
              return Container(
                height: 0.6,
                color: Styles.c_ccc,
              );
            }),
      ),
    );
  }

  ///下拉刷新
  void _onRefresh() {
    rows.clear();
    pageNum = 1;
    loadData();
  }

  @override
  bool get wantKeepAlive => true;
}
